package com.letter.otools.day.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.webkit.MimeTypeMap;

public class UriUtils {

    public static  String getFileExtension(Context context, Uri uri) {
        String extension = null;
        String mimeType = context.getContentResolver().getType(uri);
        if (mimeType != null) {
            extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
        }
        return extension;
    }


    public static String getUniversalFileName(Context context, Uri uri) {
        if (uri == null) return null;

        // 处理 DocumentProvider 的 Uri
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if (docId != null) {
                if (docId.startsWith("raw:")) {
                    return Uri.parse(docId.substring(4)).getLastPathSegment();
                } else if (docId.contains(":")) {
                    return docId.substring(docId.lastIndexOf(':') + 1);
                }
                return docId;
            }
        }

        // 处理 content:// Uri
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String fileName = getFileNameFromContentUri(context, uri);
            if (fileName != null) {
                return fileName;
            }
            // 备用方案：解析 Uri 的最后一个路径段
            return uri.getLastPathSegment();
        }

        // 处理 file:// Uri
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            String path = uri.getPath();
            if (path != null) {
                return path.substring(path.lastIndexOf('/') + 1);
            }
        }

        // 默认情况
        return uri.getLastPathSegment();
    }

    public static String getRealFileName(Context context, Uri uri) {
        if (uri == null) return null;

        String scheme = uri.getScheme();
        if (scheme == null) return null;

        switch (scheme) {
            case "content":
                return getFileNameFromContentUri(context, uri);
            case "file":
                return getFileNameFromFileUri(uri);
            default:
                return null;
        }
    }

    private static String getFileNameFromContentUri(Context context, Uri uri) {
        String fileName = null;
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                // 尝试从 DISPLAY_NAME 列获取
                int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (nameIndex != -1) {
                    fileName = cursor.getString(nameIndex);
                }

                // 如果未获取到，尝试从 _data 列获取（某些旧设备）
                if (fileName == null || fileName.isEmpty()) {
                    int dataIndex = cursor.getColumnIndex("_data");
                    if (dataIndex != -1) {
                        String path = cursor.getString(dataIndex);
                        if (path != null) {
                            fileName = path.substring(path.lastIndexOf('/') + 1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        // 如果仍未获取到，尝试从 Uri 的最后一个路径段获取
        if (fileName == null || fileName.isEmpty()) {
            fileName = uri.getLastPathSegment();
        }

        return fileName;
    }

    private static String getFileNameFromFileUri(Uri uri) {
        String path = uri.getPath();
        if (path == null) return null;
        return path.substring(path.lastIndexOf('/') + 1);
    }
}
